package de.grosjohann.android.feuerwehr.util;

import java.io.IOException;
import java.util.List;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.util.Log;

import com.google.android.maps.GeoPoint;

public final class LocationUtil {

  public static final double LAT_HOME = 51.374;
  public static final double LNG_HOME = 7.77297;

  private static final String NAME = "LocationUtil";

  public static final String LOC_HOME = LocationUtil.toString(LAT_HOME, LNG_HOME);

  public static String toString(final double lat, final double lng) {
    return lat + "," + lng;
  }

  public static String toString(final Location loc) {
    return toString(loc.getLatitude(), loc.getLongitude());
  }

  public static List<Address> getFromLocation(Context ctx, final double lat, final double lng, int maxResults)
    throws IOException {
    Geocoder gc = new Geocoder(ctx);
    return gc.getFromLocation(lat, lng, maxResults);
  }

  public static List<Address> getFromLocation(Context ctx, final Location loc, int maxResults) throws IOException {
    return getFromLocation(ctx, loc.getLatitude(), loc.getLongitude(), maxResults);
  }

  public static Address getAddress(Context ctx, String location) {
    try {
      double[] loc = getLatLng(location);
      return getFromLocation(ctx, loc[0], loc[1], 1).get(0);
    } catch (Exception ex) {
      Log.e(NAME, ex.getMessage());
      return null;
    }
  }

  public static GeoPoint getGeoPoint(String location) {
    double[] loc = getLatLng(location);

    int lat = (int) (loc[0] * 1E6);
    int lng = (int) (loc[1] * 1E6);

    return new GeoPoint(lat, lng);
  }

  private static double[] getLatLng(String location) {
    String[] loc = location.split(",", 2);

    return new double[] {Double.parseDouble(loc[0]), Double.parseDouble(loc[1]) };
  }
}
